<template>
  <div class="hello">
    <h1>信息填写</h1>
    <form @submit.prevent="submitForm">
      <ul>
        <li>
          <label for="name">姓名：</label>
          <input
            id="name"
            v-model="formData.name"
            type="text"
            required
          >
        </li>
        <li>
          <label for="age">年龄：</label>
          <input
            id="age"
            v-model="formData.age"
            type="number"
            min="0"
            required
          >
        </li>
        <li>
          <label for="email">邮箱：</label>
          <input
            id="email"
            v-model="formData.email"
            type="email"          
            >
        </li>
      </ul>
      <button type="submit">提交</button>
    </form>
    <router-view/>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router'; // 新增路由引入
interface FormData {
  name: string;
  age: number | null;
  email: string;
}

export default defineComponent({
  name: 'FormPage',
  data() {
    return {
      formData: {
        name: '',
        age: null,
        email: ''
      } as FormData
    };
  },
  setup() {
    const router = useRouter(); // 新增路由实例
    return { router };
  },
  methods: {
    async submitForm() {
      try {
        const response = await axios.post(
          'http://localhost:8011/user/adduser', // 请替换为实际接口地址
          this.formData
        );
        
        if (response.status === 200) {
          alert('提交成功');
          // 新增：提交成功后跳转到详情页
          this.router.push({
            name: 'FormDetail',
            query: { 
             formData: JSON.stringify(this.formData) // 序列化为字符串
          }
        });
          this.resetForm();
        }
      } catch (error) {
        console.error('提交失败:', error);
        alert('提交失败，请重试');
      }
    },
    resetForm() {
      this.formData = {
        name: '',
        age: null,
        email: ''
      };
    }
  }
});
</script>

<style scoped lang="less">
h1 {
  margin-bottom: 30px;
}

form {
  max-width: 500px;
  margin: 0 auto;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 15px 0;
  display: flex;
  align-items: center;
}

label {
  width: 80px;
  margin-right: 10px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #42b983;
  border-radius: 4px;
}

button {
  margin-top: 20px;
  padding: 10px 30px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  
  &:hover {
    background-color: darken(#42b983, 10%);
  }
}
</style>